package org.groovymud.object.registry.domain;

import grails.spring.BeanBuilder;
import groovy.lang.Binding;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.groovymud.object.MudObject;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.Resource;

/**
 * implementation of domain manager that loads beans using 
 * a grails beanbuilder implementation
 * @author corbym
 *
 * @param <MudObject, ObjectLocation>
 */
public class BeanBuilderDomainManager extends AbstractSuffixedScriptedDomainManager<MudObject> implements ApplicationContextAware {

	private static final Logger logger = Logger.getLogger(BeanBuilderDomainManager.class);
	private String preloadedDomains;

	public MudObject getObject(String handle) {
		MudObject bean = (MudObject) getApplicationContext().getBean(handle);
		return bean;
	}

	public void initialise() {
		if (preloadedDomains != null) {
			loadDomain(preloadedDomains);
		}
	}

	public List<String> getHandles() {
		return Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), MudObject.class));
	}

	public boolean canLoad(String domain) {
		if (domain == null) {
			throw new IllegalArgumentException("Domain string cannot be null");
		}
		boolean exists = false;
		Resource resource = getApplicationContext().getResource(domain);
		exists = resource.exists();
		if (!exists) {
			try {
				resource = getApplicationContext().getResources(domain)[0];
			} catch (IOException e) {
				e.printStackTrace();
			}
			exists = resource.exists();
		}
		return exists && resource.isReadable() && domain.length() != 0 && matchesSuffixe(domain);
	}

	public boolean contains(String handle) {
		return getApplicationContext().containsBean(handle);
	}

	public void loadDomain(String domain) {
		Binding binding = createScriptBinding();

		BeanBuilder builder = new BeanBuilder(getApplicationContext(), getEngine().getGroovyClassLoader());
		builder.setBinding(binding);
		try {
			builder.loadBeans(domain);
		} catch (IOException e) {
			logger.error(e, e);
		} finally {
			System.out.println(builder.getBeanDefinitions().keySet());
			ApplicationContext beanContext = builder.createApplicationContext();
			if (logger.isDebugEnabled()) {
				logger.debug("loaded beans from beanbuilder:" + Arrays.asList(beanContext.getBeanDefinitionNames()));
			}
			setApplicationContext(beanContext);
		}
	}

	public void removeObject(String handle) {
		GenericApplicationContext ctx = new GenericApplicationContext(getApplicationContext());
		ctx.removeBeanDefinition(handle);
	}

	/**
	 * @return the preloadedDomains
	 */
	public String getPreloadedDomains() {
		return preloadedDomains;
	}

	/**
	 * @param domains an ant glob form string, eg **\/*MudBeans.groovy
	 */
	public void setPreloadedDomains(String domains) {
		this.preloadedDomains = domains;
	}
}
